package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.mapper.WorkspaceMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceMapper workspaceMapper;

    /**
     * 营业额数据统计接口 --- 时间不间断
     *
     * @param begin
     * @param end
     * @return {@link TurnoverReportVO}
     */
    /*@Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();

        //todo 1. 获取日期
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateListString = StringUtils.join(dateList, ",");

        //todo 2. 区间获取营业额 --- 当天的营业额:订单状态为已完成(5)的金额总和以及当天时间
        //sql语句:select Sum(amount) from orders where status = 5 and order_time > beginTime and order_time < endTime
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double amount = orderMapper.sumByMap(map);
            amount = amount == null ? 0.0 : amount;
            turnoverList.add(amount);
        }
        String turnoverListString = StringUtils.join(turnoverList, ",");

        //todo 3.封装返回
        TurnoverReportVO turnoverReportVO = TurnoverReportVO
                .builder()
                .dateList(dateListString)
                .turnoverList(turnoverListString)
                .build();

        return turnoverReportVO;
    }*/

    /**
     * 营业额数据统计接口 --- 时间间断
     *
     * @param begin
     * @param end
     * @return {@link TurnoverReportVO}
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //map: [{"order_time_format":"2023-10-06","sum_amount":299},{"order_time_format":"2023-10-07","sum_amount":399},{},{},...]
        List<Map<String,Object>> list = orderMapper.selectStatisticsBetweenOrderTime(begin,end);
        /*List<String> timeArr = new ArrayList<>();
        list.forEach(item->{
            String time = (String) item.get("order_time_format");
            timeArr.add(time);
        });
        String joinedTime = String.join(",",timeArr);*/

        //todo map 优化
        String joinedTime = list.stream().map(item -> {
            String time = (String) item.get("order_time_format");
            return time;
        }).collect(Collectors.joining(","));


        /*List<String> amountArr = new ArrayList<>();
        list.forEach(item->{
            BigDecimal amount = (BigDecimal) item.get("sum_amount");
            amountArr.add(amount.toString());
        });
        String joinedAmount = String.join(",",amountArr);*/
        //todo map优化
        String joinedAmount = list.stream().map(item -> {
            String amount = item.get("sum_amount").toString();
            return amount;
        }).collect(Collectors.joining(","));

        return TurnoverReportVO.builder().dateList(joinedTime).turnoverList(joinedAmount).build();
    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return {@link UserReportVO}
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //todo 1.日期区间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //todo 3.新增用户 --- create_time < endTime
        List<Integer> newUserList = new ArrayList<>();
        //todo 2.用户总量 --- create_time>beginTime and create_time < endTime
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            Integer newCustomCount = userMapper.selectCountByTime(map);
            newUserList.add(newCustomCount);
            //新增用户 --- create_time < endTime
            map.put("begin", beginTime);
            Integer customCount = userMapper.selectCountByTime(map);
            totalUserList.add(customCount);
        }
        //todo 4.封装数据返回
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
        return userReportVO;
    }

    /*public UserReportVO userStatistics(LocalDate begin, LocalDate end){
        List<Map<String,Object>> list = orderMapper.selectStatisticsBetweenCreateTime(begin,end);
        //todo 处理时间
        String createTimeFormat = list.stream()
                .map(item -> (String) item.get("create_time_format"))
                .collect(Collectors.joining(","));
        //todo 每日新增用户数
        String countAll = list.stream()
                .map(item -> (Long)item.get("count_new"))
                .map(item -> {
                    String s = item.toString();
                    return s;
                })
                .collect(Collectors.joining(","));
        //todo 截止到当前日期的总用户数
        String countDay = list.stream()
                .map(item -> (Long) item.get("count_all"))
                .map(Object::toString)
                .collect(Collectors.joining(","));

        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(createTimeFormat);
        userReportVO.setTotalUserList(countAll);
        userReportVO.setNewUserList(countDay);

        return userReportVO;
        
    }*/

    /**
     * 订单统计接口
     *
     * @param begin
     * @param end
     * @return {@link OrderReportVO}
     */
    /*@Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //存放每日的订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //存放每日的订单有效总数
        List<Integer> validOrderCountList = new ArrayList<>();
        //todo 1.遍历时间,查询每天的订单总数,有效订单数 --- 根据 order_time 下单时间进行查询
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //todo 1.1 每日订单总数
            Integer totalOrderCount = getOrderCount(beginTime, endTime, null);
            // todo 1.2 每日有效订单总数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(totalOrderCount);
            validOrderCountList.add(validOrderCount);
        }
        //todo 2.计算订单总数 和 有效订单总数 和 订单完成率
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //orderCompletionRate 不为0
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = Double.valueOf(validOrderCount) / totalOrderCount;
        }
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate).build();
        return orderReportVO;
    }*/
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end){
        List<Map<String,Object>> list = orderMapper.selectordersStatisticsBetweenOrderTime(begin,end);
        // todo 日期
        String joinedTime = list.stream()
                .map(item -> (String) item.get("order_time_format"))
                .collect(Collectors.joining(","));

        //todo 每日订单数
        List<Long> countAllList = list.stream()
                .map(item -> {
                    Long countAll = (Long) item.get("count_all");
                    return countAll;
                })
                .collect(Collectors.toList());
        //todo 订单总数
        Optional<Long> optionalAllLong = countAllList.stream().reduce(Long::sum);
        Long totalOrderCount = 0L;
        if (optionalAllLong.isPresent()){
            totalOrderCount = optionalAllLong.get();
        }

        //todo 每日有效订单数
        List<Long> countVaildList = list.stream()
                .map(item -> {
                    Long countVaild = (Long) item.get("count_vaild");
                    return countVaild;
                })
                .collect(Collectors.toList());
        //todo 有效订单总数
        Optional<Long> optionalVaildLong = countVaildList.stream().reduce(Long::sum);
        Long validOrderCount = 0L;
        if (optionalVaildLong.isPresent()){
            validOrderCount = optionalVaildLong.get();
        }

        //todo 订单完成率
        Double orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();

        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(joinedTime);
        String joinedAll = countAllList.stream().map(Object::toString).collect(Collectors.joining(","));
        orderReportVO.setOrderCountList(joinedAll);
        String joinedVaild = countVaildList.stream().map(Object::toString).collect(Collectors.joining(","));
        orderReportVO.setValidOrderCountList(joinedVaild);
        orderReportVO.setTotalOrderCount(Math.toIntExact(totalOrderCount));
        orderReportVO.setValidOrderCount(Math.toIntExact(validOrderCount));
        orderReportVO.setOrderCompletionRate(orderCompletionRate);

        return orderReportVO;
    }

    /**
     * 查询销量排名top10接口
     *
     * @param begin
     * @param end
     * @return {@link SalesTop10ReportVO}
     */
    public SalesTop10ReportVO topStatistics(LocalDate begin, LocalDate end){
        List<Map<String,Object>> list = orderMapper.selectTopStatisticsBetweenOrderTime(begin,end);
        String joinedName = list.stream()
                .map(item -> (String) item.get("name"))
                .collect(Collectors.joining(","));
        String joinNumber = list.stream()
                .map(item -> (BigDecimal) item.get("sum"))
                .map(BigDecimal::intValue)
                .map(Object::toString)
                .collect(Collectors.joining(","));

        return SalesTop10ReportVO.builder().nameList(joinedName).numberList(joinNumber).build();
    }


    /*@Override
    public SalesTop10ReportVO topStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
        //根据时间区间查找销量前10的商品
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime,endTime);
        //获取nameList
        List<String> nameList = goodsSalesDTOList.stream().map(goodsSalesDTO -> {
            String name = goodsSalesDTO.getName();
            return name;
        }).collect(Collectors.toList());
        String nameJoin = StringUtils.join(nameList, ",");

        //获取numberList
        List<String> numberList = goodsSalesDTOList.stream().map(goodsSalesDTO -> {
            String number = goodsSalesDTO.getNumber() + "";
            return number;
        }).collect(Collectors.toList());
        String numberJoin = StringUtils.join(numberList, ",");

        SalesTop10ReportVO top10ReportVO = SalesTop10ReportVO
                .builder()
                .nameList(nameJoin)
                .numberList(numberJoin)
                .build();
        return top10ReportVO;
    }*/

    /**
     * 根据条件获取订单数
     *
     * @param begin
     * @param end
     * @param status
     * @return {@link Integer}
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        // 封装在map集合里进行查询
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

    /**
     * 导出Excel报表接口
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        try {
            //todo 获取前30天时间
            LocalDate beginDate = LocalDate.now().plusDays(-30);
            LocalDateTime begin = LocalDateTime.of(beginDate,LocalTime.MIN);
            LocalDate endDate = LocalDate.now().plusDays(-1);
            LocalDateTime end = LocalDateTime.of(endDate,LocalTime.MAX);
            BusinessDataVO businessDataVO = workspaceMapper.selectExcelDate(begin,end);

            //todo 1.读取模板
            InputStream stream = this.getClass().getClassLoader().getResourceAsStream("template/temp.xlsx");
            Workbook wb = WorkbookFactory.create(stream);

            //todo 2.查询数据进行填充
            Sheet sheet1 = wb.getSheetAt(0);
            Row row2 = sheet1.getRow(1);
            row2.getCell(1).setCellValue(beginDate+"至"+endDate);
            //todo 2.1概览数据
            //获取第4行
            Row row3 = sheet1.getRow(3);
            row3.getCell(2).setCellValue(businessDataVO.getTurnover());
            row3.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row3.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获取第5行
            Row row5 = sheet1.getRow(4);
            row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row5.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //todo 2.2 明细数据
            List<BusinessDataVO> businessDataVOList = workspaceMapper.selectExcelDayDate(begin,end);
            for (int i = 0; i < businessDataVOList.size(); i++) {
                LocalDate date = businessDataVOList.get(i).getOrderTimeFormat();
                BusinessDataVO dataVO = businessDataVOList.get(i);
                int rowIndex = i + 7;
                Row row = sheet1.getRow(rowIndex);
                BigDecimal orderCompletionRate = BigDecimal.valueOf(dataVO.getOrderCompletionRate())
                        .multiply(BigDecimal.valueOf(100))
                        .setScale(2, RoundingMode.HALF_UP);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue("$" + dataVO.getTurnover());
                row.getCell(3).setCellValue(dataVO.getValidOrderCount());
                row.getCell(4).setCellValue(orderCompletionRate + "%");
                row.getCell(5).setCellValue("$" + dataVO.getUnitPrice());
                row.getCell(6).setCellValue(dataVO.getNewUsers());
            }
            /*for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                businessDataVO = workspaceMapper.selectExcelDate(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                Row row = sheet1.getRow(7+i);
                row.getCell(1).setCellValue(beginDate.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }*/

            //todo 3.写好Excel放进响应response
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (Exception e) {
            log.error("导出excel失败:",e);
        }
    }
}
